package com.sumainfor.pc.market.service;

import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.PageUtils;
import com.sumainfor.common.utlis.Pager;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.RdHousingConMapper;
import com.sumainfor.pc.market.dao.RdHousingInfoMapper;
import com.sumainfor.pc.market.dao.RdHousingMapper;
import com.sumainfor.pc.market.feign.Zfeign.ZpcEpcFeign;
import com.sumainfor.pc.market.feign.Zfeign.ZzuulFeign;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date 2018年11月7日
 * @Describe 工程部查询房源配置
 */
@Service
public class RdHousingService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(RdHousingService.class);// 日志

    @Autowired
    private RdHousingMapper rdHousingMapper;
    @Autowired
    private RdHousingInfoMapper RdHousingInfoMapper;
    @Autowired
    private RdHousingConMapper rdHousingConMapper;
    @Autowired
    private RdHousingInfoMapper rdHousingInfoMapper;
    @Autowired
    private ZzuulFeign ZzuulFeign;
    @Autowired
    private ZpcEpcFeign zpcEpcFeign;

    /**
     * @return result
     * @Author
     * @Date 2018年11月7日
     * @Describe 房源池查询所有的房源
     */
    public List<Map<String, Object>> getCommunityList(Map<String, Object> params) {
        return rdHousingMapper.getCommunityList(params);
    }

    /**
     * 查询房源总数
     *
     * @param params
     * @return
     */
    public Integer getCommunityListCount(Map<String, Object> params) {
        return rdHousingMapper.getCommunityListCount(params);
    }

    /**
     * 根据房源编号查询房源的信息
     */
    public Map<String, Object> getHousingByHouId(Map<String, Object> params) {
        Map<String, Object> map = rdHousingMapper.getHousingByHouId(params);
        //到网关查询房源的所属服务中心、归属管家、收房专员
        Map<String, Object> zuulMap = ZzuulFeign.getHousingInfoName(map);
        if (zuulMap != null) {
            map.putAll(zuulMap);
        }
        return map;
    }

    /**
     * 查询整套房源的房间信息
     */
    public List<Map<String, Object>> getHousingAllByHouId(Map<String, Object> params) {
        return rdHousingMapper.getHousingAllByHouId(params);
    }

    /**
     * 运营部租后主管维修跟踪查询房源信息
     */
    public List<Map<String, Object>> getHouInfoListForRepair(Map<String, Object> params) {
        return rdHousingMapper.getHouInfoListForRepair(params);
    }

    /**
     * 运营部给房源分配服务管家的房源列表
     */
    public List<Map<String, Object>> getHouInfoListForButler(Map<String, Object> params) {
        List<Map<String, Object>> list = rdHousingMapper.getHouInfoListForButler(params);
        //保存服务管家的员工编号
        List<String> idList = new ArrayList<String>();
        for (Map<String, Object> map : list) {
            if (map.get("SysUserId") != null && !map.get("SysUserId").equals("")) {
                idList.add(map.get("SysUserId").toString());
            }
        }
        System.out.println("idList:" + idList);
        System.out.println("idList:" + idList.size());
        if (idList.size() > 0) {
            //查询网关的服务管家的姓名
            JsonResult zuulMap = ZzuulFeign.getButlerName(idList);
            List<Map<String, Object>> zuulList = (List<Map<String, Object>>) zuulMap.get("result");
            for (Map<String, Object> map : zuulList) {
                for (Map<String, Object> map2 : list) {
                    if (MapUtils.getString(map, "user_id").equals(MapUtils.getString(map2, "SysUserId"))) {
                        map2.putAll(map);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 运营部给房源分配服务管家的房源列表
     */
    public Integer getHouInfoListCountForButler(Map<String, Object> params) {
        return rdHousingMapper.getHouInfoListCountForButler(params);
    }

    /**
     * 查询房源的全部图片
     */
    public Map<String, Object> getHouImage(Map<String, Object> params) {
        //查询整套房源的图片
        Map<String, Object> map = rdHousingMapper.getHouImageByHouId(params);
        //查询各个房间的图片
        List<Map<String, Object>> list = RdHousingInfoMapper.getHouInfoImageByHouId(params);
        if (list != null) {
            map.put("houInfoImgList", list);
        }
        return map;
    }

    /**
     * 修改盈利预测，给房源分配管家
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateHousingSysUserId(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                System.out.println("前端传递的参数:" + params);
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                Integer count = rdHousingMapper.updateHousingSysUserId(params);
                if (count > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("服务器繁忙");
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 租赁顾问修改房源主表图片
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateHousingImg(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                System.out.println("前端传递的参数:" + params);
                //获取各个房间的集合
                List<Map<String, Object>> list = (List<Map<String, Object>>) params.get("dataList");
                if (params.get("HouId") == null) {
                    log.info("修改房源主表，缺少房源主表编号");
                    return result.putFailed("缺少参数");
                }
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                //修改房源主表图片
                Integer count = rdHousingMapper.updateHousingImg(params);
                if (count != null) {
                    Map<String, Object> hMap = new HashMap<String, Object>();
                    hMap.put("updtm", params.get("updtm"));
                    hMap.put("updterm", params.get("updterm"));
                    hMap.put("updby", params.get("updby"));
                    hMap.put("updfnc", params.get("updfnc"));
                    for (Map<String, Object> hoMap : list) {
                        if (hoMap.get("HouCon") != null) {
                            hMap.putAll(hoMap);
                            //修改房源配置主表的图片
                            rdHousingConMapper.updateHousingConImg(hMap);
                        }
                    }
                    result.putSuccess("操作成功");
                } else {
                    log.info("房屋主表图片修改错误");
                    result.putFailed("服务器繁忙");
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 服务管家验房上传图片
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateHoHousingImg(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                System.out.println("前端传递的参数:" + params);
                //获取各个房间的集合
                String HouseImg = params.get("HouseImg").toString();
                String ShowImg = params.get("ShowImg").toString();
                String DiningFile = params.get("DiningFile").toString();
                String KitchenFile = params.get("KitchenFile").toString();
                String ToiletFile = params.get("ToiletFile").toString();
//                int ifImg=1;// 0未全部上传 1 全部上传
                List<Map<String, Object>> list = (List<Map<String, Object>>) params.get("dataList");
                if (HouseImg.equals("") || ShowImg.equals("") || DiningFile.equals("") || KitchenFile.equals("")
                        || ToiletFile.equals("") || list.size() == 0) {
                    params.put("ifImg", 0);
                }
                if (params.get("HouId") == null) {
                    log.info("修改房源主表，缺少房源主表编号");
                    return result.putFailed("缺少参数");
                }
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                //修改房源主表图片
                Integer count = rdHousingMapper.updateHousingImg(params);
                if (count != null) {
                    Map<String, Object> hMap = new HashMap<String, Object>();
                    hMap.put("updtm", params.get("updtm"));
                    hMap.put("updterm", params.get("updterm"));
                    hMap.put("updby", params.get("updby"));
                    hMap.put("updfnc", params.get("updfnc"));
                    for (Map<String, Object> hoMap : list) {
                        if (hoMap.get("HouCon") != null) {
                            hMap.putAll(hoMap);
                            //修改房源配置主表的图片
                            rdHousingConMapper.updateHousingConImg(hMap);
                        }
                    }
                    System.out.println("ssssssswssssssssssss");
                    if (params.get("ifImg").toString().equals("1")) {//0 图片未全部上传  1表示已经全部上传
                        JsonResult epcResult = zpcEpcFeign.updateIfCheckStateaHo(params);
                        if (epcResult.get("errorCode").toString().equals("0")) {
                            //状态 1草稿 2.待审核 3已审核（待装修） 4.装修中 5装修完成 6.验房中 7验房通过
                            params.put("State", "7");
                            params.put("HouState", "1");//房源状态预销   0不能预销    1可以预销
                            rdHousingMapper.updateHousingState(params);
                            params.put("State", "0");//房源状态（0 待上架 1可签约 2已签约 ）
                            params.put("HouState", "2");//预销状态（0 不能预销 1可以预销 2 可签约）
                            params.put("Accepted", params.get("updtm"));//验房时间
                            rdHousingInfoMapper.updateHouAccepted(params);
                            System.out.println("全部上传完成");
                            result.putSuccess("操作成功");
                        } else {
                            result.putFailed("修改失败");
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        }
                    } else {
                        result.putSuccess("操作成功");
                    }
                } else {
                    log.info("房屋主表图片修改错误");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    result.putFailed("服务器繁忙");
                }
            } catch (Exception e) {
                result.put("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 运营部服务管家录入水电燃表数查询房源信息列表
     */
    public List<Map<String, Object>> getHoList(Map<String, Object> params) {
        return rdHousingMapper.getHoList(params);
    }

    /**
     * 运营部服务管家录入水电燃表数查询房源信息列表总数
     */
    public Integer getHoListCount(Map<String, Object> params) {
        return rdHousingMapper.getHoListCount(params);
    }

    /**
     * 服务管家抄表的时候查询房源居住中的租客编号
     */
    public JsonResult getTenantListByTenId(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (params.get("HouIdList") == null) {
            return result.putFailed("参数不正确");
        }
        List<String> HouIdList = (List<String>) params.get("HouIdList");
        List<Map<String, Object>> list = rdHousingMapper.getTenantListByTenId(params);
        if (list != null) {
            result.put(list);
        } else {
            result.putFailed("服务器繁忙");
        }
        return result;
    }

    /**
     * 租后主管查询员工的信息列表（服务管家和服务秘书）
     */
    public JsonResult getRdStaffList(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        List<Map<String, Object>> list = rdHousingMapper.getRdStaffList(params);
        if (list != null) {
            result.put(list);
        } else {
            result.putFailed("服务器繁忙");
        }
        return result;
    }

    /**
     * 查询房源的配置变更列表总数（服务管家配置变更记录、服务中心经理配置变更记录）
     */
    public JsonResult getRdAlterList(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        PageUtils pageUtils = new PageUtils();
        Pager pager = new Pager();
        pager.setPageno(Integer.parseInt(params.get("pageno").toString()));
        pager.setPagesize(Integer.parseInt(params.get("pagesize").toString()));
        pager.setPagerNecessary(params, pager);
        Integer cout = rdHousingMapper.getRdAlterListCount(params);
        if (cout == 0) {
            return pageUtils.getJsonResult(new ArrayList<Map<String, Object>>(), params, cout);
        }
        List<Map<String, Object>> getCommunityList = rdHousingMapper.getRdAlterList(params);
        result = pageUtils.getJsonResult(getCommunityList, params, cout);
        return result;
    }

}
